package com.wanmait.meteor.controller;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wanmait.meteor.pojo.Manager;
import com.wanmait.meteor.service.ManagerService;
import com.wanmait.meteor.util.JWTUtils;
import com.wanmait.meteor.util.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/manager")
public class ManagerController {

    @Resource
    private ManagerService managerService;

    //金 检查注册的手机号是否存在
    @PostMapping("checkManagerPhone")
    public Result checkManagerPhone(@RequestBody Manager manager){
        boolean flag = managerService.checkManagerPhone(manager.getManagerPhone());
        return Result.success(flag);
    }

    //金 查出所有enable为1的manager
    @PostMapping("allManager")
    public Result allManager(int pageNum){
        String str = "page_size";
        int PageSize = managerService.getPageSize(str);
        PageInfo<Manager> pageInfo = managerService.findAll(pageNum,PageSize);
        return Result.success(pageInfo);
    }

    //金 检查注册的账号是否已存在
    @PostMapping("checkManagerAccount")
    public Result checkManagerAccount(@RequestBody Manager manager){
        Boolean flag = managerService.checkManagerAccount(manager.getManagerAccount());
        return Result.success(flag);
    }

    //金 超级管理员添加管理员
    @PostMapping("register")
    public Result managerAdd(@RequestBody Manager manager){
        managerService.addManager(manager);
        return Result.success("成功");
    }

    //金 管理员登录并创建token且返回
    @PostMapping("login")
    public Result managerLogin(@RequestBody Manager manager, String code, HttpServletRequest request) {
//        System.out.println(code);
//        System.out.println(manager.getManagerAccount());
//        System.out.println(manager.getManagerPass());
//        boolean flag = managerService.checkCode(code,request);

//        HttpSession session = request.getSession();
//        String sessionCode = (String) session.getAttribute("code");

//        System.out.println(sessionCode);
//        if (code.equalsIgnoreCase(sessionCode)) {
            Manager loginManager = managerService.login(manager);
            if(loginManager==null)
            {
                return Result.fail("没有用户");
            }
            else
            {
                String token = JWTUtils.createToken(loginManager);
                boolean managerType = loginManager.getManagerType();

                JSONObject jsonObject =new JSONObject();
                jsonObject.put("token",token);
                jsonObject.put("managerType",managerType);

                jsonObject.put("loginManager",loginManager);
                return Result.success(jsonObject);
            }
//        }
//        else{
//            return Result.fail("验证码输入错误");
//        }
    }
}
